﻿using Castle.Core.Configuration;
using Inovout.Application;
using Inovout.Web.Mvc;
using Inovout.YunYao.Models;
using Inovout.YunYao.Services;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace Inovout.YunYao.Emulator.Web.Controllers
{
    [AllowAnonymous]
    public class MonitoringNodeController : RepositoryController<MonitoringNode>
    {
        public ActionResult Send(int id)
        {
            MonitoringNode monitoringNode = base.RepositoryService.FindById(id);
            ISolutionApplicationService solutionApplicationService
                = ComponentRegistry.Resolve<ISolutionApplicationService>();
            ViewBag.Token = solutionApplicationService.FindBySolutionId(monitoringNode.Solution.Id).Token;
            return View(monitoringNode);
        }

        public ActionResult PostNode()
        {
            IApplication application = ComponentRegistry.Resolve<IApplication>();
            IConfiguration receiverConfiguration = application.Configuration.Children.SingleOrDefault(c => c.Name.Equals("receiver"));

            WebRequest webRequest = WebRequest.Create(receiverConfiguration.Attributes["node_uri"].Trim());
            webRequest.Method = "POST";
            webRequest.Headers.Add("appkey", Request.Form["appkey"]);
            webRequest.Headers.Add("token", Request.Form["token"]);
            byte[] buffer = new byte[Request.InputStream.Length];
            Request.InputStream.Read(buffer, 0, buffer.Length);
            webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
            WebResponse webResponse = webRequest.GetResponse();
            return Content(new StreamReader(webResponse.GetResponseStream()).ReadToEnd());
        }
    }
}
